package com.ljtxxhwj.myblob.controller;

import com.ljtxxhwj.myblob.entity.Comment;
import com.ljtxxhwj.myblob.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/comments.do")
public class CommentController {

    private final CommentService commentService;

    @Autowired
    public CommentController(CommentService commentService) {
        this.commentService = commentService;
    }

    // 根据文章ID查询所有评论
    @GetMapping("/article/{articleId}.do")
    public List<Comment> getCommentsByArticleId(@PathVariable Integer articleId) {
        return commentService.getCommentsByArticleId(articleId);
    }

    // 插入一个新的评论
    @PostMapping
    public ResponseEntity<Comment> addComment(@RequestBody Comment comment) {
// 获取当前的日期和时间

        // 创建一个 Timestamp 对象
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        // 将 Timestamp 转换为 java.sql.Date
        java.sql.Date sqlDate = new java.sql.Date(timestamp.getTime());

        // 设置评论日期
        comment.setCommentDate(sqlDate);
        commentService.addComment(comment);
        return new ResponseEntity<>(comment, HttpStatus.CREATED);
    }

    // 根据评论ID查询评论
    @GetMapping("/{commentId}.do")
    public Comment getCommentById(@PathVariable Integer commentId) {
        return commentService.getCommentById(commentId);
    }

    // 更新评论内容
    @PutMapping("/{commentId}.do")
    public ResponseEntity<String> updateCommentContent(
            @PathVariable Integer commentId,
            @RequestBody Comment updatedComment) {
        commentService.updateCommentContent(commentId, updatedComment.getCommentContent());
        return new ResponseEntity<>("Comment updated successfully", HttpStatus.OK);
    }

    // 删除评论
    @DeleteMapping("/{commentId.do}")
    public ResponseEntity<String> deleteCommentById(@PathVariable Integer commentId) {
        commentService.deleteCommentById(commentId);
        return new ResponseEntity<>("Comment deleted successfully", HttpStatus.OK);
    }

    // 查询所有评论
    @GetMapping
    public List<Comment> getAllComments() {
        return commentService.getAllComments();
    }
    // 根据评论ID查询直接回复该评论的子评论列表
    @GetMapping("/{commentId}/replies.do")
    public List<Comment> getRepliesByCommentId(@PathVariable Integer commentId) {
        return commentService.getRepliesByCommentId(commentId);
    }

    // 辅助方法，用于获取所有层级的子评论
    @GetMapping("/{commentId}/all-replies.do")
    public List<Comment> getCommentWithAllReplies(@PathVariable Integer commentId) {
        return commentService.getCommentWithAllReplies(commentId);
    }

}